package com.leo;

import cn.hutool.core.io.file.FileWriter;

import java.io.File;

/**
 * @ClassName StrBinaryTurnUtil
 * @Description 字符串和二进制互相转换工具类
 * @Author wangss
 * @date 2021.03.01 17:17
 * @Version 1.0
 */
public class StrBinaryTurnUtil {

    /**
     * 字符串转换为二进制
     *
     * @param str
     */
    public static String strToBinary(String str) {
        char[] chars = str.toCharArray();
        String result = "";
        for (int i = 0; i < chars.length; i++) {
            result += Integer.toBinaryString(chars[i]) + " ";
        }
        return result;
    }

    /**
     * 将二进制字符串转换成int数组
     *
     * @param binStr
     * @return
     */
    public static int[] binStrToIntArray(String binStr) {
        char[] temp = binStr.toCharArray();
        int[] result = new int[temp.length];
        for (int i = 0; i < temp.length; i++) {
            result[i] = temp[i] - 48;
        }
        return result;
    }

    /**
     * 将二进制转换成字符
     *
     * @param binStr
     * @return
     */
    public static char binStrToChar(String binStr) {
        int[] temp = binStrToIntArray(binStr);
        int sum = 0;
        for (int i = 0; i < temp.length; i++) {
            sum += temp[temp.length - 1 - i] << i;
        }
        return (char) sum;
    }

    /**
     * 将二进制转换为字符串
     *
     * @param binStr
     * @return
     */
    public static String binStrToStr(String binStr) {
        String[] tempStr = binStr.split(" ");
        char[] tempChar = new char[tempStr.length];
        for (int i = 0; i < tempStr.length; i++) {
            tempChar[i] = binStrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }

    public static void main(String[] args) {
        System.out.println(strToBinary("李栋"));
        System.out.println(binStrToStr("110011101001110 110100000001011"));

        File file = new File("D:/test.txt");
        FileWriter fileWriter = FileWriter.create(file);
        fileWriter.write(binStrToStr("110011101001110 110100000001011"));
        fileWriter.append(strToBinary("李栋"));
    }

}
